package 重温_Java并发基础.CompletableFuture案例.商店信息查询模型;

import java.util.List;
import java.util.Random;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

/**
 * @author idea
 * @data 2020/2/21
 */
public class Shop {

    private String name;

    private Random random=new Random(1500);

    public Shop(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public double getPrice() {
        return calculatePrice(name);
    }

    public Future<Double> getPriceAsync() {
        CompletableFuture<Double> completableFuture = new CompletableFuture<>();
        new Thread(() -> {
            double price = calculatePrice(name);
            completableFuture.complete(price);
        }).start();
        return completableFuture;
    }


    public static void delay() {
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }



    public double calculatePrice(String productNo) {
        delay();
        return random.nextInt(1500);
    }


    public static void main(String[] args) {
        Shop shop=new Shop("asd");
        long start=System.currentTimeMillis();
        Future<Double> futurePrice=shop.getPriceAsync();
        long invocationTime=System.nanoTime()-start/1_000_000;
        System.out.println("invocation return after: "+invocationTime);
        try {
            double price = futurePrice.get();
            System.out.println("price is "+price);

        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }

        long retrievalTime = ((System.nanoTime() - start) / 1_000_000);
        System.out.println("Price returned after " + retrievalTime + " msecs");
    }
}
